package mail

import (
	"errors"
	"fmt"
	"github.com/prometheus/common/log"
	"io"
)

// Message is struct used to send msg
type Message struct {
	Subject   string
	Content   io.Reader         // support html content
	To        []string          // to address string
	Extension map[string]string // message extension
}

// Sender is interface for sender
type Sender interface {
	// Send send mail
	Send(msg *Message) error
	// AsyncSend async send mail need callback func
	AsyncSend(msg *Message, handle func(err error)) error
}

// Send is func to send mail
func Send(msg *Message) (err error) {
	if sender != nil {
		err = sender.Send(msg)
	}
	return
}

// AsyncSend is func to async send mail
func AsyncSend(msg *Message, handle func(err error)) (err error) {
	go func() {
		if rec := recover(); rec != nil {
			log.Error("send mail panic", rec)
			err = errors.New(fmt.Sprintf("%v", rec))
		}
	}()
	if sender != nil {
		err = sender.AsyncSend(msg, handle)
	}
	return
}
